/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package store

import (
	"fmt"
	"path/filepath"
	"strings"

	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain/keyvaluestore"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/core"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/iam"
	"github.com/pkg/errors"
)

const (
	DIR_CERT        = "cert"
	FILE_SUFFIX_PEM = "pem"
	FILE_SUFFIX_KEY = "key"
)

func NewFileKeyStore(cryptoConfigIAMPath string) (core.KVStore, error) {
	opts := &keyvaluestore.FileKeyValueStoreOptions{
		Path: cryptoConfigIAMPath,
		KeySerializer: func(key interface{}) (string, error) {
			pkk, ok := key.(*iam.PrivKey)
			if !ok {
				return "", errors.New("converting key to PrivKey failed")
			}
			if pkk == nil || pkk.IAMID == "" || pkk.ID == "" {
				return "", errors.New("invalid key")
			}
			path, err := cryptoConfigCertOrKeyPath(cryptoConfigIAMPath, pkk.ID, FILE_SUFFIX_KEY)
			if err != nil {
				return "", err
			}
			return path, nil
		},
	}
	return keyvaluestore.New(opts)
}

func cryptoConfigCertOrKeyPath(cryptoConfigIAMPath, id, suffix string) (string, error) {
	_, orgName := filepath.Split(filepath.Dir(filepath.Dir(filepath.Dir(cryptoConfigIAMPath))))
	r := strings.NewReplacer("{userName}", strings.ToLower(id), "{username}", strings.ToLower(id))
	dir := filepath.Join(r.Replace(cryptoConfigIAMPath), DIR_CERT)
	path := filepath.Join(dir, fmt.Sprintf("%s@%s.%s", strings.ToLower(id), orgName, suffix))

	//if _, err := os.Stat(path); os.IsNotExist(err) {
	//	return "", err
	//}
	return path, nil
}
